<template>
  <div class="app-container">
    <el-form :inline="true">
      <el-form-item>
        <el-button type="primary" @click="showAddDialog()">
          <el-icon><Plus /></el-icon> 新增
        </el-button>
      </el-form-item>
      <el-form-item>
        <el-input v-model="search" placeholder="输入学期名">
          <template #append>
            <el-button><el-icon><Search /></el-icon></el-button>
          </template>
        </el-input>
      </el-form-item>
    </el-form>

    <el-table
      v-loading="listLoading"
      :data="filteredList" 
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column align="center" label="ID" width="40px">
        <template #default="scope">
          {{ scope.$index + 1 }} 
        </template>
      </el-table-column>
      <el-table-column label="学期名" prop="semesterName" align="center">
        <template #default="scope">
          {{ scope.row.semesterName }}
        </template>
      </el-table-column>
      <el-table-column
        label="学期总周数"
        prop="semesterWeeksSum"
        width="100"
        align="center"
      >
        <template #default="scope">
          <span>{{ scope.row.semesterWeeksSum }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="学期开始日"
        prop="semesterStartDate"
        align="center"
      >
        <template #default="scope">
          {{ scope.row.semesterStartDate }}
        </template>
      </el-table-column>
      <el-table-column label="学期结束日" prop="semesterEndDate" align="center">
        <template #default="scope">
          {{ scope.row.semesterEndDate }}
        </template>
      </el-table-column>
      <el-table-column label="排课状态" prop="semesterStatus" align="center">
        <template #default="scope">
          {{ scope.row.semesterStatus == 0 ? "未排课" : "已排课" }}
        </template>
      </el-table-column>

      <el-table-column align="center" prop="action" label="操作">
        <template #default="scope">
          <span>
            <el-button @click="showUpdateDialog(scope.row)" type="primary">
              <el-icon><Edit /></el-icon> 更新
            </el-button>
            <el-button @click="handleDelete(scope.row)" type="danger">
              <el-icon><Delete /></el-icon> 删除
            </el-button>
          </span>
        </template>
      </el-table-column>
    </el-table>
    <!-- el-pagination 组件已移除 -->

    <!-- 弹窗 -->
    <el-dialog v-model="dialogFormVisible" :title="form.id == null ? '新增学期' : '更新学期'">
      <el-form :model="form" label-width="120px" ref="formRef">
        <el-form-item label="学期名" prop="semesterName">
          <el-input v-model="form.semesterName"></el-input>
        </el-form-item>

        <el-form-item label="学期总周数" prop="semesterWeeksSum">
          <el-input-number
            v-model="form.semesterWeeksSum"
            :disabled="form.semesterStatus == 1"
            controls-position="right"
          ></el-input-number>
        </el-form-item>

        <el-form-item label="开始日期" prop="semesterStartDate">
          <el-col :span="11">
            <el-date-picker
              type="date"
              placeholder="选择日期"
              v-model="form.semesterStartDate"
              style="width: 100%"
              :picker-options="pickerOptions"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            >
            </el-date-picker>
          </el-col>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="onSubmit">{{ 
            form.id == null ? "添加" : "更新" 
          }}</el-button>
          <el-button @click="dialogFormVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'; // 移除了 getCurrentInstance，如果未使用
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus, Search, Edit, Delete } from '@element-plus/icons-vue'; // 引入图标
import axios from 'axios';

const list = ref([]);
const listLoading = ref(true);
const search = ref('');
// const currentPage = ref(1); // 移除
// const pagesize = ref(5);    // 移除
const dialogFormVisible = ref(false);

const form = reactive({
  id: null,
  semesterName: '',
  semesterWeeksSum: 0,
  semesterStartDate: '',
  semesterStatus: 0,
});

const formRef = ref(null); // 用于引用表单实例

const pickerOptions = {
  disabledDate(time) {
    // 限制只能选周一
    const date = new Date(time);
    return date.getDay() !== 1; // 周日是0，周一是1，...，周六是6
  },
};

const filteredList = computed(() => {
  if (!search.value) {
    return list.value;
  }
  return list.value.filter(
    (data) =>
      data.semesterName.toLowerCase().includes(search.value.toLowerCase())
  );
});

// const paginatedData = computed(() => { // 移除
//   return filteredList.value.slice(
//     (currentPage.value - 1) * pagesize.value,
//     currentPage.value * pagesize.value
//   );
// });

// const handleSizeChange = (val) => { // 移除
//   pagesize.value = val;
// };

// const handleCurrentChange = (val) => { // 移除
//   currentPage.value = val;
// };

const getList = async () => {
  listLoading.value = true;
  try {
    const res = await axios.get('/api/semester/getList', {
      headers: {
        'token': localStorage.getItem('token'),
      },
    });
    console.log(res);
    
    list.value = res.data.data;
  } catch (error) {
    console.error('Failed to fetch list:', error);
    ElMessage.error('获取列表失败');
  } finally {
    listLoading.value = false;
  }
};

const resetForm = () => {
  form.id = null;
  form.semesterName = '';
  form.semesterWeeksSum = 0;
  form.semesterStartDate = '';
  form.semesterStatus = 0;
  // if (formRef.value) {
  //   formRef.value.resetFields(); // 如果需要重置校验状态
  // }
};

const showAddDialog = () => {
  resetForm();
  dialogFormVisible.value = true;
};

const showUpdateDialog = (semester) => {
  // 直接赋值，确保响应性
  form.id = semester.id;
  form.semesterName = semester.semesterName;
  form.semesterWeeksSum = semester.semesterWeeksSum;
  form.semesterStartDate = semester.semesterStartDate;
  form.semesterStatus = semester.semesterStatus;
  dialogFormVisible.value = true;
};

const add = async () => {
  try {
    await axios.post('/api/semester', form, {
      headers: {
        token: localStorage.getItem('token'),
      },
    });
    ElMessage.success('添加成功!');
    getList();
    dialogFormVisible.value = false;
  } catch (error) {
    console.error('Failed to add semester:', error);
    ElMessage.error('添加失败');
  }
};

const update = async () => {
  try {
    await axios.put('/api/semester', form, {
      headers: {
        token: localStorage.getItem('token'),
      },
    });
    ElMessage.success('更新成功!');
    getList();
    dialogFormVisible.value = false;
  } catch (error) {
    console.error('Failed to update semester:', error);
    ElMessage.error('更新失败');
  }
};

const onSubmit = () => {
  if (form.id == null) {
    add();
  } else {
    update();
  }
};

const handleDelete = (semester) => {
  ElMessageBox.confirm(
    `将会删除学期 ${semester.semesterName} 关联的所有课表，是否继续？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {      
      try {
        await axios.delete('/api/semester/' + semester.id, {
          headers: {
            token: localStorage.getItem('token'),
          },
        });
        ElMessage.success('删除成功!');
        getList();
      } catch (error) {
        console.error('Failed to delete semester:', error);
        ElMessage.error('删除失败');
      }
    })
    .catch(() => {
      ElMessage.info('操作已取消');
    });
};

onMounted(() => {
  getList();
});

</script>

<style scoped>
.app-container {
  padding: 20px;
}
/* 你可以根据需要添加或修改样式 */
</style>
